package com.lin.vueblog.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.vueblog.common.lang.Result;
import com.lin.vueblog.entity.Blog;
import com.lin.vueblog.service.BlogService;
import com.lin.vueblog.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.rmi.runtime.Log;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lcw
 * @since 2021-04-04
 */
@Slf4j
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;
    /**
     * 博客列表页
     * @param currentPage
     * @return
     */
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){

        //mp执行分页
        Page page = new Page(currentPage, 5);

        IPage pageData = blogService.page(page,new QueryWrapper<Blog>().orderByDesc("created"));//根据创建时间倒序
        return Result.succ(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客已删除");

        return Result.succ(blog);
    }

    /**
     * 编辑+添加统一体页面
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/blog/edit")
    public Result detail(@Validated @RequestBody Blog blog){

        log.info(blog.toString());
        Blog temp = null;

        //判断是添加还是编辑
        if (blog.getId() != null){//编辑
            temp = blogService.getById(blog.getId());
            //只能编辑自己的文章
            Assert.isTrue(temp.getUser_id().longValue() == ShiroUtil.getProfile().getId().longValue(),"没有权限编辑");

        }else {//添加

            temp = new Blog();
            temp.setUser_id(ShiroUtil.getProfile().getId());
            temp.setCreated(Timestamp.valueOf(LocalDateTime.now()));
            temp.setStatus(0);
        }

        log.info(temp.toString());

        BeanUtils.copyProperties(blog,temp,"id","user_id","created","status");

        log.info(temp.toString());

        //保存编辑的内容或更新新博客
        blogService.saveOrUpdate(temp);

        return Result.succ(null);
    }
}
